import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt

# 读取数据
data_path = "./students.xlsx"
df = pd.read_excel(data_path)

# 数据预处理：将类别数据编码为数字
label_encoders = {}
for column in df.columns:
    le = LabelEncoder()
    df[column] = le.fit_transform(df[column])
    label_encoders[column] = le

# 循环进行聚类分析与可视化
for k in range(2, 6):
    # 聚类分析
    kmeans = KMeans(n_clusters=k, random_state=42)
    df['Cluster'] = kmeans.fit_predict(df)

    # PCA降维到2D
    pca = PCA(n_components=2)
    pca_result = pca.fit_transform(df.drop(columns=['Cluster']))
    df['PCA1'] = pca_result[:, 0]
    df['PCA2'] = pca_result[:, 1]

    # 可视化
    plt.figure(figsize=(8, 6))
    plt.scatter(df['PCA1'], df['PCA2'], c=df['Cluster'], cmap='viridis', s=50)
    plt.title(f"Clustering Visualization for k={k}")
    plt.xlabel("PCA1")
    plt.ylabel("PCA2")
    plt.colorbar(label='Cluster')
    plt.show()
